/**
 * arcCHAT 聊天API封装
 */

import axiosInstance from '../utils/axios'
import axios from 'axios'
import { getOrCreateClientSessionId } from '../utils/clientSession'

// 创建专用的聊天API实例，设置更长的超时时间（5分钟，适用于BLAST和Foldseek搜索）
const chatAxiosInstance = axios.create({
  baseURL: axiosInstance.defaults.baseURL,
  timeout: 300000,  // 5分钟超时（300秒），因为BLAST搜索可能需要较长时间
  headers: {
    'Content-Type': 'application/json'
  }
})

// 添加请求拦截器（如果需要token等）
chatAxiosInstance.interceptors.request.use(
  config => {
    // 如果需要token，可以从axiosInstance获取
    const token = localStorage.getItem('admin_token') || localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
chatAxiosInstance.interceptors.response.use(
  response => response,
  error => {
    if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
      error.message = '请求超时，BLAST搜索可能需要较长时间，请稍后再试或缩短序列长度'
    }
    return Promise.reject(error)
  }
)

export const chatAPI = {
  /**
   * 发送消息
   * @param {string|null} sessionId - 会话ID(null则创建新会话)
   * @param {string} message - 消息内容
   * @param {boolean} stream - 是否流式响应
   * @returns {Promise} 响应数据
   */
  sendMessage(sessionId, message, stream = false) {
    const clientSessionId = getOrCreateClientSessionId()
    return chatAxiosInstance.post('/api/chat/send', {
      session_id: sessionId,
      message: message,
      stream: stream,
      client_session_id: clientSessionId
    })
  },

  /**
   * 获取对话历史
   * @param {string} sessionId - 会话ID
   * @returns {Promise} 会话信息和消息列表
   */
  getHistory(sessionId) {
    const clientSessionId = getOrCreateClientSessionId()
    return axiosInstance.get('/api/chat/history', {
      params: { 
        session_id: sessionId,
        client_session_id: clientSessionId
      }
    })
  },

  /**
   * 获取会话列表
   * @param {number} page - 页码
   * @param {number} pageSize - 每页数量
   * @returns {Promise} 会话列表
   */
  getSessions(page = 1, pageSize = 20) {
    const clientSessionId = getOrCreateClientSessionId()
    return axiosInstance.get('/api/chat/sessions', {
      params: { 
        page, 
        page_size: pageSize,
        client_session_id: clientSessionId
      }
    })
  },

  /**
   * 删除会话
   * @param {string} sessionId - 会话ID
   * @returns {Promise}
   */
  deleteSession(sessionId) {
    const clientSessionId = getOrCreateClientSessionId()
    return axiosInstance.delete(`/api/chat/session/${sessionId}`, {
      params: {
        client_session_id: clientSessionId
      }
    })
  },

  /**
   * 清空所有会话(只清空当前客户端的会话)
   * @returns {Promise}
   */
  clearAll() {
    const clientSessionId = getOrCreateClientSessionId()
    return axiosInstance.post(`/api/chat/clear-all?client_session_id=${encodeURIComponent(clientSessionId)}`)
  }
}

export default chatAPI
